<!-- ERC-设备巡检-巡检任务 -->
<template>
  <div>
    <div v-show="isMain" class="equip-wrap-common inspect-wrap-common">
      <!-- 搜索功能 -->
      <px-form ref="formRef" class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="所属计划编号">
              <px-input
                v-model="queryParams.planCode"
                placeholder="输入计划编号"
                maxlength="50"
                clearable
                @blur="queryParams.planCode = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="任务名称">
              <px-input
                v-model="queryParams.taskCodeOrName"
                placeholder="输入任务名称/编号"
                maxlength="50"
                clearable
                @blur="queryParams.taskCodeOrName = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <!-- 科室 -->
          <px-col :span="6">
            <EquipClassSelect :className="queryParams.className" @changeClassName="changeClassName" />
          </px-col>
          <!-- 状态 -->
          <px-col :span="6">
            <px-form-item label="状态" prop="taskStatusList">
              <px-select
                v-model="queryParams.taskStatusList"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="2"
                placeholder="请选择状态"
                clearable
                filterable
              >
                <px-option v-for="item in statusList" :key="item.value" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="开始时间" prop="startTimeRange">
              <px-date-picker
                v-model="queryParams.startTimeRange"
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="changeDate"
              />
            </px-form-item>
          </px-col>
          <!-- 提交人员 -->
          <px-col :span="6">
            <px-form-item label="提交人员" prop="executorId">
              <px-select-v2
                v-model="queryParams.executorId"
                style="width: 100%"
                filterable
                clearable
                :options="approvalList"
                placeholder="请选择提交人员"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <!-- 表格功能 -->
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 303px)" border>
        <px-table-column label="序号" min-width="50" align="center" fixed="left">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </px-table-column>
        <template v-for="(item, index) in tableColumns" :key="index">
          <px-table-column
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <template v-if="item.prop === 'taskCode'" #default="scope">
              <span v-if="isHasPermission('ALL_EQUIP_INSPECT_TASK_DETAIL')" style="color: #3b82f6; cursor: pointer" @click="handleView(scope.row)">{{
                scope.row.taskCode
              }}</span>
              <span v-else>{{ scope.row.taskCode }}</span>
            </template>
            <template v-else-if="item.type === 'status'" #default="scope">
              <px-tag :type="tagArr[scope.row['taskStatus']]">{{ scope.row["taskStatusDesc"] }}</px-tag>
              <!-- <div class="status">
                <div class="circle" :style="{ backgroundColor: `${tagBgColorList[scope.row.taskStatus]}` }" />
                <p :style="{ color: `${tagBgColorList[scope.row.taskStatus]}` }">
                  {{ scope.row.taskStatusDesc }}
                </p>
              </div> -->
            </template>
            <template v-else #default="scope">{{
              scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
            }}</template>
          </px-table-column>
        </template>
        <!-- 表格按钮功能 -->
        <px-table-column fixed="right" label="操作" min-width="160" align="center">
          <template #default="scope">
            <px-tooltip content="查看详情" placement="top">
              <px-button v-has="'ALL_EQUIP_INSPECT_TASK_DETAIL'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.createBy === userId && [1, 2, 3].includes(scope.row.taskStatus)" content="取消任务" placement="top">
              <px-button v-has="'ALL_EQUIP_INSPECT_TASK_CANCEL'" link type="primary" icon="CloseCircle" @click="handleCancel(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="scope.row.executorId === userId && [4, 5].includes(scope.row.taskStatus)" content="执行任务" placement="top">
              <px-button v-has="'ALL_EQUIP_INSPECT_TASKFORM_PAGE'" link type="primary" icon="DocumentChecked" @click="handleTodo(scope.row)" />
            </px-tooltip>
            <px-tooltip v-if="[2].includes(scope.row.taskStatus) && scope.row.isInGroup" content="领取任务" placement="top">
              <px-button v-has="'ALL_EQUIP_INSPECT_TASK_COLLECT'" link type="primary" icon="DocumentAdd" @click="handleCollect(scope.row)" />
            </px-tooltip>
            <px-tooltip
              v-if="[4, 5].includes(scope.row.taskStatus) && (scope.row.executorId === userId || scope.row.planCreateBy === userId)"
              content="转派任务"
              placement="top"
            >
              <px-button v-has="'ALL_EQUIP_INSPECT_TASK_FORWARD'" link type="primary" icon="Position" @click="handleForward(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
    </div>
    <!-- 巡检任务详情 -->
    <InspectTaskDetail
      v-if="!isMain && isView"
      :isMain="isMain"
      :isView="isView"
      :taskId="taskId"
      @backMainPage="backMainPage"
      @queryTable="queryTable"
    />
    <!-- 转派任务 -->
    <ForwardDialog
      v-if="changeAcceptorVisible"
      :visible="changeAcceptorVisible"
      :rowData="taskData"
      @closeDialog="changeAcceptorVisible = false"
      @queryTable="queryTable"
    />
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "ERC_INSPECT_TASK"
});
import { cancelTask, collectTask, queryInspectTask, queryTaskStatus } from "@/api/equip/inspectTask";
import { isHasPermission } from "@/utils/auth";
import { stringTrimOfParams } from "@/utils/common";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { onBeforeMount, onMounted, reactive, ref, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import ForwardDialog from "./components/ForwardDialog.vue"; // 转派弹窗
import InspectTaskDetail from "./components/InspectTaskDetail.vue";


const route = useRoute();
const router = useRouter();
const formRef = ref();
const tagArr = ["info", "info", "warning", "warning", "primary", "primary", "success", "success", "primary"];
const state = reactive<any>({
  isMain: true, // 主页面true 其他页面false
  isView: false, // 详情true 其他false
  isAdd: false, // 新增编辑true 其他false
  taskData: "",
  taskId: "",
  userId: "",
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  total: 0,
  tableColumns: [
    { prop: "taskCode", label: "任务(工单)编号", minWidth: "150", showOverflowTooltip: true, fixed: "left" },
    { prop: "planCode", label: "所属计划编号", minWidth: "150", showOverflowTooltip: true },
    { prop: "taskName", label: "任务名称", minWidth: "240", showOverflowTooltip: true },
    { prop: "startTime", label: "任务开始时间", minWidth: "160", showOverflowTooltip: true },
    { prop: "classNameDesc", label: "科室", minWidth: "60", showOverflowTooltip: true },
    { prop: "taskStatusDesc", label: "状态", minWidth: "100", type: "status", showOverflowTooltip: true },
    { prop: "groupCodeName", label: "执行组", minWidth: "160", showOverflowTooltip: true },
    { prop: "executorName", label: "提交人员", minWidth: "150", showOverflowTooltip: true }
  ],
  tableData: [],
  detailPageType: "add",
  changeAcceptorVisible: false,
  planNo: "",
  statusList: [], //状态
  approvalList: [] //执行人
});
const {
  isView,
  userId,
  isMain,
  taskData,
  taskId,
  isAdd,
  queryParams,
  tableColumns,
  total,
  tableData,
  changeAcceptorVisible,
  statusList,
  approvalList
} = toRefs(state);

const tagBgColorList = {
  0: "#909399", // 已取消
  1: "#909399", // 未开始
  2: "#F59E0B", // 待接单
  3: "#F59E0B", // 待接单超期
  4: "#3B82F6", // 执行中
  5: "#3B82F6", // 执行中超期
  6: "#10B981", // 已完成
  7: "#10B981" // 已完成超期
};

onBeforeMount(() => {
  const {
    query: { taskCode }
  } = route;
  const {
    query: { PlanCode }
  } = route;
  if (route?.query && route?.query?.className) {
    queryParams.value.className = route?.query?.className;
  } else {
    queryParams.value.className = "";
  }
  if (route?.query && route?.query?.taskStatusList) {
    queryParams.value.taskStatusList = (route?.query?.taskStatusList as string)?.split("-");
  } else {
    queryParams.value.taskStatusList = [];
  }
  if (taskCode) {
    // 1、reffer, taskNo存在——表明来自其他页面，访问任务详情页
    isMain.value = false;
    isView.value = true;
  } else if (PlanCode) {
    //从计划页面带着计划编号过来的
    queryParams.value.planCode = PlanCode;
    queryTable();
  } else {
    // 2、reffer, taskNo不存在——表明访问任务列表页
    queryTable();
  }
});

// 来源下拉框
const queryClassNameSelect = async () => {
  statusList.value = await queryTaskStatus();
};

// 进入页面时触发
onMounted(async () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  userId.value = userInfo.userId;
  approvalList.value = await getEmployeeIdAndName();
  queryClassNameSelect();
  queryTable();
});
// 科室组件调用父组件--科室
const changeClassName = val => {
  queryParams.value.className = val;
};

// 获取开始日期及结束日期
const changeDate = val => {
  if (val && val.length > 0) {
    queryParams.value.startTime = val[0];
    queryParams.value.endTime = val[1];
  } else {
    queryParams.value.startTime = "";
    queryParams.value.endTime = "";
  }
};
// 分页查询任务列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  const data = await queryInspectTask(stringTrimOfParams(params));
  tableData.value = data?.data;
  total.value = data?.total;
};

// 重置筛选条件和巡检清单
const resetTable = async () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 20
  };
  queryTable();
};

// 关闭所有页面
const handleClose = () => {
  isAdd.value = false;
  isMain.value = false;
  isView.value = false;
};
//返回主页面
const backMainPage = () => {
  handleClose();
  isMain.value = true;
};
// 跳转详情
const handleView = (row: any) => {
  handleClose();
  taskId.value = row.id;
  isView.value = true;
  isMain.value = false;
};
// 取消任务
const handleCancel = (row: any) => {
  const { id, taskName } = row;
  PxMessageBox.confirm(`确认取消巡检任务“${taskName}”吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await cancelTask(id);
      PxMessage.success("取消成功");
      queryTable();
    })
    .catch(() => {});
};
// 执行任务
const handleTodo = (row: any) => {
  const { fullPath } = route;
  const newFullPath = encodeURIComponent(fullPath);
  router.push(`/all/equip/inspect/task/form?id=${row.id}&page=${newFullPath}`);
};
// 领取任务
const handleCollect = (row: any) => {
  const { id, taskName } = row;
  PxMessageBox.confirm(`确认领取巡检任务“${taskName}”吗？领取后其他人将不可再接单`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    draggable: true,
    type: "warning"
  })
    .then(async () => {
      await collectTask(id);
      PxMessage.success("领取成功");
      // handleExecute();
      const { fullPath } = route;
      const newFullPath = encodeURIComponent(fullPath);
      router.push(`/all/equip/inspect/task/form?id=${id}&page=${newFullPath}`);
    })
    .catch(() => {});
};
// 转派
const handleForward = (row: any) => {
  changeAcceptorVisible.value = true;
  taskData.value = row;
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.status {
  display: flex;
  flex-direction: row;
  align-items: center;

  .circle {
    width: 8px;
    height: 8px;
    margin-right: 5px;
    border-radius: 50%;
  }
}
</style>
